package com.hmdp.service.impl;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.LoginFormDTO;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.User;
import com.hmdp.mapper.UserMapper;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RegexUtils;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.LOGIN_CODE_KEY;
import static com.hmdp.utils.RedisConstants.LOGIN_USER_KEY;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Autowired
    private  RedisTemplate<String, Object> redisTemplate;
    @Autowired
    private UserMapper userMapper;
    @Override
    public Result senCode(String phone, HttpSession session) {
        //检验手机号是否合法
        if(RegexUtils.isPhoneInvalid(phone))
        {
            //不合法,返回错误信息
            return Result.fail("手机号不合法");
        }
        //合法
        else {
            //生成验证码
            String s = RandomUtil.randomNumbers(6);
            //设置有效期
            redisTemplate.opsForValue().set(LOGIN_CODE_KEY+phone, s,2, TimeUnit.MINUTES);
            log.info("验证码发送成功:{}",s);
            return Result.ok();
        }
    }

    @Override
    public Result login(LoginFormDTO loginForm, HttpSession session) {

        //校验手机号
        if(RegexUtils.isPhoneInvalid(loginForm.getPhone())){
            //手机号不合法
            return Result.fail("手机号不合法");
        }
        else {
            //获取验证码
            String code = (String)redisTemplate.opsForValue().get(LOGIN_CODE_KEY+loginForm.getPhone());
            //验证码一致
            if(code.trim().equals(loginForm.getCode())){
                //是否为新用户
                User user = userMapper.seleteUserByPhone(loginForm.getPhone());
                //不是新用户
                if(user==null){
                    user = new User();
                    user.setPhone(loginForm.getPhone());
                    user.setNickName("user_"+RandomUtil.randomString(10));
                    int row = userMapper.insertUser(user);
                }
                String token = UUID.randomUUID().toString();
                //把user转成userDto
                UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);
                log.info("userDTO:{},已放入Thread",userDTO);
                UserHolder.saveUser(userDTO);
                //将user转成map
                Map<String, Object> userMap = BeanUtil.beanToMap(userDTO, new HashMap<>(), CopyOptions.create()
                        .setIgnoreNullValue(true)
                        .setFieldValueEditor((fieldName, fieldValue) -> fieldValue.toString()));
                String tokenKey = LOGIN_USER_KEY+token;
                redisTemplate.opsForHash().putAll(tokenKey,userMap);
                //给token设置有效时间
                redisTemplate.expire(tokenKey,30,TimeUnit.MINUTES);
                return Result.ok(token);
            }
            else
            {
                return Result.fail("验证码不一致");
            }
        }
    }
}
